from maze import *
import random

class MazeBuilder(object):
    def __init__(self, maze, seed=None):
        self.maze = maze
        self.r = random.Random(seed)
        self.used = {}

    def add_cell(self, x, y, d):
        self.used[(x, y)] = True

        exits = []
        for dir in all_dirs:
            tx, ty = dir.from_cell(x, y)
            if self.maze.inside(tx, ty) and not self.used.has_key((tx, ty)):
                exits.append(dir)

        self.r.shuffle(exits)
        for dir in exits:
            nx, ny = dir.from_cell(x, y)
            if not self.used.has_key((nx, ny)):
                self.maze.open_passage(x, y, dir)
            self.add_cell(nx, ny, dir)

    def build_maze(self):
        sx, sy = 0, 0

        self.maze.open_passage(0, 0, NORTH)
        self.add_cell(sx, sy, SOUTH)
        self.maze.open_passage(self.maze.width-1, self.maze.height-1, SOUTH)

